<?php

namespace app\admin\controller;

use app\helpers\Common;
use app\common\model\Admin;

use support\Request;
use think\facade\Db;
use think\facade\Cache;
use think\Exception;
use app\BaseController;

class AuthController extends BaseController
{
    /**
     * Login
     */
    public function login(Request $request)
    {
        $session_admin = session('admin');
        if ($session_admin && !empty($session_admin['id'])) {
            return redirect(url('/index/index'));
        }

        return view('auth/login');
    }

    /**
     * Ajax Login
     */
    public function doLogin(Request $request)
    {
        try {
            if ($request->post()) {
                $param = $request->all();
                $name = trim($param['name']);
                $password = trim($param['password']);
                $remember = $param['remember'] ?? 0;

                if (!$name) {
                    throw new Exception('登录名不能为空！');
                }
                if (!$password) {
                    throw new Exception('密码不能为空！');
                }

                $where = [
                    'name' => $name,
                ];
                $adminInfo = Db::name('admins')->where($where)->field('*')->find();
                if (!$adminInfo) {
                    throw new Exception('您的用户名不存在！');
                }
                if (!password_verify($password, $adminInfo['password'])) {
                    throw new Exception('密码错误！');
                }
                $captcha_code = trim($param['captcha_code']);
                $captcha_key = $param['captcha_key'] ?? '';
                if ($captcha_code) {
                    $verifyObj = new \app\common\service\Verify();
                    if (!$verifyObj->check($captcha_code, $captcha_key)) {
                        throw new Exception('验证码错误！');
                    }
                }

                $adminInfo = Admin::formatItem($adminInfo);

                $code = 200;
                $msg = '登录成功';
                $url = url('/dashboard/index');

                $id = $adminInfo['id'];
                // 记录登录时间及IP等信息
                $data = [
                    'last_login_time' => time(),
                    'last_login_ip' => get_IP(),
                ];
                $record = Admin::where('id', $id)->update($data);
                if (!$record) {
                    throw new Exception('服务异常，请重新登录！');
                }
                //session('ADMIN', $adminInfo);
                //$adminInfo = json_decode(json_encode($adminInfo), true);
                session(['admin' => $adminInfo]);
                // 记住密码
                if ($remember) {
                    cookie('admin', json_encode($adminInfo), 3600*24*7);
                }
                // 日志
                Common::adminLog($request, '管理员登录');
            } else {
                throw new Exception('请求方式不正确');
            }
        } catch (Exception $e) {
            $code = 0;
            $msg = $e->getMessage();
            $url = url('/auth/login');
        }

        $data = array(
            'code' => $code,
            'msg' => $msg,
            'data' => [
                'url' => $url,
            ]
        );

        return json($data, 200);
    }

    /**
     * Logout
     */
    public function logout(Request $request)
    {
        //session('admin', null);
        $request->session()->forget('admin');
        cookie('admin', null);

        Cache::tag('admin')->clear();

        return redirect(url('/auth/login'));
    }
}
